package cn.tedu.log.aop;

import cn.tedu.annotations.LogOperation;
import cn.tedu.log.mapper.LogMapper;
import cn.tedu.log.pojo.entity.Log;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Aspect
@Component
public class OperationLogAspect {
    @Autowired
    private LogMapper logMapper;

    @Pointcut("@annotation(cn.tedu.annotations.LogOperation)")
    public void logOperation() {
    }

    @Before("logOperation()")
    public void recordOperationLog(JoinPoint joinPoint) {
        // 获取当前登录的管理员信息
        Integer managerId = getCurrentManagerId();

        // 获取请求相关信息
        String uri = getRequestUri();
        String act = getRequestAct();
        String ipAddress = getIpAddress();
        Integer modelId = getRequestModelId();
        Integer objectId = getRequestObjectId();

        // 获取操作描述
        LogOperation logOperation = (LogOperation) joinPoint.getSignature().getDeclaringType().getAnnotation(LogOperation.class);
        String operationDescription = logOperation.value();

        // 创建日志对象并保存到数据库
        Log systemLog = new Log();
        systemLog.setManagerId(managerId);
        systemLog.setContent(operationDescription);
        systemLog.setUri(uri);
        systemLog.setAct(act);
        systemLog.setIp(ipAddress);
        systemLog.setModelId(modelId);
        systemLog.setObjectId(objectId);
        systemLog.setCreateTime(new Date());

        // 保存日志
        logMapper.insert(systemLog);
    }

    private Integer getRequestObjectId() {
        return 0;
    }

    private Integer getRequestModelId() {
        return 1;
    }

    // 假设的方法，实际使用时需要替换为真实的方法实现
    private Integer getCurrentManagerId() {
        return 2;
    }

    private String getRequestUri() {
        return "";
    }

    private String getRequestAct() {
        return "";
    }

    private String getIpAddress() {
        return "";
    }
}